# Create your views here.
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.template import Template, Context, RequestContext
from django.template.loader import get_template
from django.shortcuts import render_to_response
from django.db import connection
from django.core.mail import send_mail
from app.models import Publisher, Book
from app.forms import ContactForm

import datetime, os
from django.template import RequestContext


class Person(object):
    def __init__(self, first_name, last_name):
        self.first_name, self.last_name = first_name, last_name


def getTime(request):
    now = datetime.datetime.now()
    html = "<html><body>It is now %s</body></html>" % now
    print ">>> hello wong"
    return HttpResponse(now)


def index(request):
    now = datetime.datetime.now()
    t = get_template("current_datetime.html")
    html = t.render(Context({'current_date': now, "wong": "hello wong"}))
    return HttpResponse(html)


def home(request):
    now = datetime.datetime.now()
    template_name = "current_datetime.html"
    list = ["one", "two", "three", "four", "five"]
    path = str(request.META.get("PYTHONPATH", "none")) + "/"
    return render_to_response(template_name,
                              {"now": now, "jian": "hello jian", "athlete_list": False, "list": list, "path": path})


def hours_ahead(request, offset):
    try:
        offset = int(offset)
    except ValueError:
        raise Http404()

    dt = datetime.datetime.now() + datetime.timedelta(hours=offset)
    html = "<span>%s</span><br><span>%s</span>" % (offset, dt)
    return HttpResponse(html)


def dbTest(request):
    #p1=Publisher(name='Address',address="zhichun_road",city="beijing",state_province="hebei" ,country="china",website="www.taikongfeizhu.com")
    p2 = Publisher(name='jenking', address="nongye_road", city="zhengzhou", state_province="henan", country="china",
                   website="www.qq.com")
    #p2.name="wong"
    p2.save()
    #p=Publisher.objects.filter(id=10).update(name='huangs')
    return HttpResponse("get ready!!")


def form(request):
    values = request.META.items()
    values.sort()
    html = []
    for k, v in values:
        html.append("<tr><td>%s</td><td>%s</td></tr>" % (k, v))

    path = request.META.get("PATH", "none")
    #return HttpResponse('<table border="1">%s</table>'%'\n'.join(html))
    return HttpResponse(str(path))


def contact_form(request):
    errors = []
    if request.method == 'POST':
        if not request.POST.get('subject', ''):
            errors.append('Enter a subject.')
        if not request.POST.get('message', ''):
            errors.append('Enter a message.')
        if request.POST.get('email') and '@' not in request.POST['email']:
            errors.append('Enter a valid e-mail address.')
        if not errors:
            return HttpResponseRedirect('/home/')

    return render_to_response("contact_form.html",
                              {'titleName': 'contact_form', 'errors': errors,
                               'subject': request.POST.get('subject', ''),
                               'email': request.POST.get('email', ''), 'message': request.POST.get('message', '')},
                              context_instance=RequestContext(request))


def querystring(request):
    error = []
    if 'q' in request.GET:
        q = request.GET["q"]
        if not q:
            error.append("Enter a search term.")
        elif len(q) > 20:
            error.append("Please enter at most 20 characters.")
        else:
            books = Book.objects.filter(title__icontains=q)
            return render_to_response('new_form.html', {'books': books, 'query': q})
    return render_to_response("new_form.html", {'error': error})


def search_form(request):
    error = False
    if 'q' in request.POST:
        q = request.POST["q"]
        if not q:
            error = True
        else:
            return render_to_response("search_form.html", {"info": q, "titleName": "search-form"},
                                      context_instance=RequestContext(request))
    return render_to_response("search_form.html", {"error": error, "titleName": "search-form"},
                              context_instance=RequestContext(request))


def forms(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            return HttpResponseRedirect('/home/')
    else:
        form = ContactForm(
            initial={'subject': 'I Love this site', 'email': '497761497@qq.com', 'message': 'hello'}
        )
    return render_to_response("forms_obj.html", {'form': form, 'title': 'forms-title'},
                              context_instance=RequestContext(request))


def entry_list(request):
    obj_list = Publisher.objects.all()
    return render_to_response("temp2.html", {"obj_list": obj_list, "title": "blog"})


def custom_proc(request):
    return {
        'app': "My app",
        "user": "wong",
        "ip_address": request.META['REMOTE_ADDR'],
        "data": "<b>man</b>"
    }


def view_1(request):
    t = get_template("temp1.html")
    c = RequestContext(
        request, {'message': 'I am view 1.'}, processors=[custom_proc]
    )
    res = t.render(c)
    return HttpResponse(res)


def view_2(request):
    return render_to_response('temp1.html', {'message': 'I am view 2', 'user': 'huangjian'},
                              context_instance=RequestContext(request, processors=[custom_proc]))



















